import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yi_shop/model/favorable.dart';
import 'package:yi_shop/route/index.dart';
import 'package:yi_shop/ui/scroll_refresh_config.dart';
import 'package:yi_shop/utils/colors.dart';
import 'package:yi_shop/utils/styles.dart';
import 'package:yi_shop/utils/svg.dart';
import 'package:yi_shop/utils/tools.dart';

class FavorableChoiceController extends GetxController {
  RxList<FavorableChoiceModel> pageList = RxList([]);

  RefreshController refreshController = RefreshController();

  RxInt total = 45.obs;

  @override
  void onInit() {
    initData();
    super.onInit();
  }

  Future<void> onRefresh() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));
    refreshController.refreshCompleted(resetFooterState: true);
  }

  Future<void> onLoading() async {
    /// 发起请求
    await Future.delayed(const Duration(milliseconds: 2000));

    /// if failed, use loadFailed(), if no data return, use LoadNodata()
    if (pageList.length > total.value) {
      return refreshController.loadNoData();
    }

    /// 添加数据
    initData();

    /// 完毕
    refreshController.loadComplete();
  }

  void initData() {
    var r = Random.secure();
    for (var i = 0; i < 10; i++) {
      pageList.add(FavorableChoiceModel(
          name: '平底包头凉鞋女2019夏季新款网红女鞋韩版百搭后空一字带',
          price: r.nextInt(499).toDouble(),
          imgUrl:
              'https://img.alicdn.com/img/i2/31164671/O1CN01xs4bXA1kNMvAemD8m_!!0-saturn_solar.jpg_360x360xzq75.jpg_.webp'));
    }
  }
}

class FavorableChoicePage extends GetView<FavorableChoiceController> {
  const FavorableChoicePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: ToolsUtils.builderLeading(),
        title: Text(
          '优惠精选',
          style: StylesUtils.customTextStyle(
            fontWeight: FontWeight.w700,
            fontSize: StylesUtils.fontSize18,
          ),
        ),
        actions: [
          IconButton(
              onPressed: ToolsUtils.openShare,
              icon: SvgUtils.assetName('u3577', width: 20, height: 20)),
          IconButton(
              onPressed: () {
                Get.toNamed(RoutePath.shopCart);
              },
              icon: SvgUtils.assetName('u3578', width: 24, height: 20)),
        ],
      ),
      body: Obx(() => scrollRefreshConfig(context)),
    );
  }

  ScrollRefreshConfig scrollRefreshConfig(BuildContext context) {
    return ScrollRefreshConfig(
      refreshController: controller.refreshController,
      onRefresh: controller.onRefresh,
      onLoading: controller.onLoading,
      child: listViewBuilder(context),
    );
  }

  ListView listViewBuilder(BuildContext context) {
    return ListView.builder(
      padding: EdgeInsets.symmetric(horizontal: (Get.width - 345) / 2),
      itemBuilder: (BuildContext context, int index) {
        final row = controller.pageList[index];
        return InkWell(
          onTap: () {
            Get.toNamed(RoutePath.productNormalInfo);
          },
          child: Container(
            padding: EdgeInsets.all(12.w),
            margin: EdgeInsets.only(top: 15.h),
            decoration:
                BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(5.r)),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              textDirection: TextDirection.ltr,
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(5.r),
                  child: CachedNetworkImage(
                    imageUrl: row.imgUrl,
                    width: 90,
                    height: 90,
                    fit: BoxFit.fill,
                  ),
                ),
                Expanded(
                    child: Container(
                  padding: EdgeInsets.only(left: 10.w),
                  child: Column(
                    children: [
                      Align(
                        alignment: Alignment.topLeft,
                        child: Text(
                          row.name,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: StylesUtils.customTextStyle(
                              color: ColorsUtils.color3333,
                              fontSize: StylesUtils.fontSize13,
                              lineHeight: 1.2.h),
                        ),
                      ),
                      Container(
                        alignment: Alignment.centerLeft,
                        margin: EdgeInsets.only(top: 25.w),
                        child: Text(
                          '￥${row.price}',
                          style: StylesUtils.customTextStyle(color: ColorsUtils.colorF048),
                        ),
                      )
                    ],
                  ),
                ))
              ],
            ),
          ),
        );
      },
      itemCount: controller.pageList.length,
    );
  }
}
